package com.boang.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/*
  @author: 13813
  @date: 2024/9/6 12:29
*/
@Component
@Data
@ConfigurationProperties(prefix = "jwt")
public class JwtTokenUtils {
    private long expired;
    private String signature;

    public String generateToken(String username) throws UnsupportedEncodingException {
        return JWT.create()
                .withSubject("icar")
                .withExpiresAt(new Date(System.currentTimeMillis() + expired))
                .withClaim("username", username)
                .sign(Algorithm.HMAC256(signature));
    }

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        String sign = JWT.create().
                withSubject("subject").
                withExpiresAt(new Date(System.currentTimeMillis() + 1000)).
                withClaim("username", "aaa").
                sign(Algorithm.HMAC256("q123"));
        System.out.println(sign);
    }

    public String extractClaim(String token) throws UnsupportedEncodingException {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(signature)).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        return verify.getClaim("username").asString();
    }
}
